﻿/*
 * EmeCoder v1.2.1.168
 * 作者：Administrator/PC4APPLE
 * 时间：2013-04-08 21:38:20
 * 版权：版权所有 (C) Eme Development Team 2013
*/

﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;
using HmFramework;
using HmFramework.Data;

namespace CuteSprite.Eme.Data.CRM
{
	/// <summary>快件收件员工</summary>
	[Serializable]
	[ModelCheckMode(ModelCheckModes.CheckTableWhenFirstUse)]
	public class ExpressRecipient : ExpressRecipient<ExpressRecipient> { }

	/// <summary>快件收件员工</summary>
	public partial class ExpressRecipient<TEntity> : Entity<TEntity> where TEntity : ExpressRecipient<TEntity>, new()
	{
		#region 对象操作﻿

		static ExpressRecipient()
		{
			// 用于引发基类的静态构造函数，所有层次的泛型实体类都应该有一个
			TEntity entity = new TEntity();
		}

		/// <summary>验证数据，通过抛出异常的方式提示验证失败。</summary>
		/// <param name="isNew"></param>
		public override void Valid(Boolean isNew)
		{
			//// 这里验证参数范围，建议抛出参数异常，指定参数名，前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
			//if (Name.IsNullOrWhiteSpace()) { throw new ArgumentNullException(__.Name, _.Name.DisplayName + "不能为空！"); }
			//if (!isNew && ID < 1) { throw new ArgumentOutOfRangeException(__.ID, _.ID.DisplayName + "必须大于0！"); }

			// 建议先调用基类方法，基类方法会对唯一索引的数据进行验证
			base.Valid(isNew);

			// 在新插入数据或者修改了指定字段时进行唯一性验证，CheckExist内部抛出参数异常
			//if (isNew || Dirtys[__.Name]) CheckExist(__.Name);

			if (isNew)
			{
				//if (!Dirtys[__.CreateOn]) { CreateOn = DateTime.Now; }
				CreateOn = DateTime.Now;
			}
		}

		#endregion

		#region 扩展属性﻿

		//[NonSerialized]
		//private Express _Express;
		/// <summary>该快件收件员工所对应的客户快件</summary>
		[XmlIgnore]
		public Express Express
		{
			get
			{
				return Extends.GetExtend<Express, Express>("Express", e => Express.FindByID(ExpressID));
				//if (_Express == null && ExpressID > 0 && !Dirtys.ContainsKey("Express"))
				//{
				//	_Express = Express.FindByID(ExpressID);
				//	Dirtys["Express"] = true;
				//}
				//return _Express;
			}
			set { Extends.SetExtend<Express>("Express", value); }
		}

		#endregion

		#region 扩展查询﻿

		/// <summary>根据收件员工查找</summary>
		/// <param name="staffid">收件员工</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByStaffID(Int32 staffid)
		{
			if (Meta.Count > 1000)
				return FindAll(_.StaffID, staffid);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.StaffID, staffid);
		}

		/// <summary>根据员工所属部门查找</summary>
		/// <param name="organizeid">员工所属部门</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByOrganizeID(Int32 organizeid)
		{
			if (Meta.Count > 1000)
				return FindAll(_.OrganizeID, organizeid);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.OrganizeID, organizeid);
		}

		/// <summary>根据快件查找</summary>
		/// <param name="expressid">快件</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByExpressID(Int32 expressid)
		{
			if (Meta.Count > 1000)
				return FindAll(_.ExpressID, expressid);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(_.ExpressID, expressid);
		}

		/// <summary>根据主键查找</summary>
		/// <param name="id">主键</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindByID(Int32 id)
		{
			if (Meta.Count > 1000)
				return Find(_.ID, id);
			else // 实体缓存
				return Meta.Cache.Entities.Find(_.ID, id);
			// 单对象缓存
			//return Meta.SingleCache[id];
		}

		#endregion

		#region 高级查询

		// 以下为自定义高级查询的例子

		///// <summary>
		///// 查询满足条件的记录集，分页、排序
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>实体集</returns>
		//[DataObjectMethod(DataObjectMethodType.Select, true)]
		//public static EntityList<TEntity> Search(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindAll(SearchWhere(key), orderClause, null, startRowIndex, maximumRows);
		//}

		///// <summary>
		///// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>记录数</returns>
		//public static Int32 SearchCount(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindCount(SearchWhere(key), null, null, 0, 0);
		//}

		///// <summary>构造搜索条件</summary>
		///// <param name="key">关键字</param>
		///// <returns></returns>
		//private static String SearchWhere(String key)
		//{
		//	// WhereExpression重载&和|运算符，作为And和Or的替代
		//	// SearchWhereByKeys系列方法用于构建针对字符串字段的模糊搜索
		//	var exp = SearchWhereByKeys(key, null);

		//	// 以下仅为演示，Field（继承自FieldItem）重载了==、!=、>、<、>=、<=等运算符（第4行）
		//	//if (userid > 0) exp &= _.OperatorID == userid;
		//	//if (isSign != null) exp &= _.IsSign == isSign.Value;
		//	//if (start > DateTime.MinValue) exp &= _.OccurTime >= start;
		//	//if (end > DateTime.MinValue) exp &= _.OccurTime < end.AddDays(1).Date;

		//	return exp;
		//}

		#endregion

		#region 扩展操作

		/// <summary>根据快件、员工创建快件收件人员信息</summary>
		/// <param name="expressID"></param>
		/// <param name="staffID"></param>
		/// <param name="user"></param>
		/// <returns></returns>
		public static TEntity Create(Int32 expressID, Int32 staffID, IAdministrator user)
		{
			ValidationHelper.ArgumentNull(user, "user");

			var entity = new TEntity();
			entity.ExpressID = expressID;
			var staff = user.FindStaffByID(staffID);
			if (staff != null)
			{
				entity.OrganizeID = staff.OrganizeID;
				entity.StaffID = staffID;
			}
			entity.CreateOn = DateTime.Now;
			entity.CreateUserID = user.ID;
			entity.CreateBy = user.Name;
			return entity;
		}

		#endregion

		#region 业务

		/// <summary>快件收件人员保存</summary>
		/// <param name="expressID"></param>
		/// <param name="ids"></param>
		/// <param name="user"></param>
		public static void GrantAll(Int32 expressID, String ids, IAdministrator user)
		{
			List<Int32> staffIDs;
			if (ids.IsNullOrWhiteSpace())
			{
				staffIDs = new List<Int32>();
			}
			else
			{
				staffIDs = new List<Int32>(ids.SplitDefaultSeparator<Int32>());
			}
			GrantAll(expressID, staffIDs, user);
		}

		/// <summary>快件收件人员保存</summary>
		/// <param name="expressID"></param>
		/// <param name="staffIDs"></param>
		/// <param name="user"></param>
		public static void GrantAll(Int32 expressID, List<Int32> staffIDs, IAdministrator user)
		{
			ValidationHelper.ArgumentNull(user, "user");
			if (expressID < 1) { return; }

			var es = FindAllByExpressID(expressID);
			// 删除快件之前的收件员工信息
			if (es != null) { es.Delete(); }

			foreach (var item in staffIDs)
			{
				var entity = Create(expressID, item, user);
				entity.Save();
			}
		}

		#endregion
	}
}